import { _decorator, Color, Component, Label, Node, Sprite, tween, UITransform, Vec3 } from 'cc';
import { UICtrl } from '../../../Framework/Managers/UICtrl';
import { Door_Ctrl } from './Door_Ctrl';
import { EventMgr } from '../../../Framework/Managers/EventMgr';
import { Globle } from '../../../Framework/Utils/Globle';
const { ccclass, property } = _decorator;

@ccclass('Room_Ctrl')
export class Room_Ctrl extends UICtrl {

    private roomBox:Node;
    private roomPath:Node;
    private bossPath:Node;
    private selectImg:Sprite;
    private door:Door_Ctrl;
    
    roomId:number = 0;
    pathArr:Vec3[] = [];
    bossPathArr:Vec3[] = [];

    onLoad(): void {
        super.onLoad();
        this.roomBox = this.getChildOrComponent("RoomBox");
        this.roomPath = this.getChildOrComponent("RoomPath");
        this.bossPath = this.getChildOrComponent("BossPath");
        this.selectImg = this.getChildOrComponent("SelectImg",Sprite);
        this.door = this.getChildOrComponent("Door",Door_Ctrl);
        this.AddButtonListener("SelectImg",this,this.selectThisRoom);
        this.AddMessage("SelectRoom");
    }

    recvMsg(cmd: string, data: any): void {
        switch (cmd) {
            case "SelectRoom":
                this.selectImg.color = new Color(255,255,255,this.roomId == data ? 255:0);
                break;
            default:
                break;
        }
    }

    /**选中此房间 */
    selectThisRoom(){
        if (!Globle.isCanSelect) return;
        EventMgr.Instance.Emit("SelectRoom",this.roomId);
    }
    /**设置门状态 0关闭 1开启 */
    setDoorState(state){
        if (state == 0) {
            this.door.closeDoor();
        }else{
            this.door.openDoor();
        }
    }
    /**获取一个房间内的随机位置 */
    getRandomPosInRoom(){
        let posNode:Node = this.roomBox.children[Math.floor(Math.random()*this.roomBox.children.length)];
        let randomPos = new Vec3(0,0,0);
        let trans = posNode.getComponent(UITransform);
        let wid = trans.width - 15; //15是player预制体身体的宽高的一半，为了限时的时候预留出来不让玩家卡墙
        let hei = trans.height - 15;
        randomPos.x = posNode.position.x + Math.random()*wid-wid/2;
        randomPos.y = posNode.position.y + Math.random()*hei-hei/2;
        return randomPos;
    }

    /**获取玩家进入房间的路径数据 */
    getRoomPathByPlayer(){
        this.pathArr = [];
        for (let i = 0; i < this.roomPath.children.length; i++) {
            this.pathArr.push(this.roomPath.children[i].position);
        }
        let endPos = this.getRandomPosInRoom();
        this.pathArr.push(endPos);
        return this.pathArr;
    }
    /**获取boss进入房间的路径数据 */
    getRoomPathByBoss(){
        this.bossPathArr = [];
        for (let i = 0; i < this.bossPath.children.length; i++) {
            this.bossPathArr.push(this.bossPath.children[i].position);
        }
        return this.bossPathArr;
    }
}


